package com.tingyuge.base.jdk.io.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @Created by xiaodao
 */
public class ReadHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel serverChanel;
    public ReadHandler(AsynchronousSocketChannel channel) {
        this.serverChanel = channel;
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        if(result==-1){//客户端主动停止了tcp套接字,这时候服务端也可以停止了
            try {
                serverChanel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        attachment.flip();
        byte[] message = new byte[attachment.remaining()];
        attachment.get(message);

        try {
            String body = new String(message,"UTF-8");
            System.out.println("server  接受的 message : "+ body);

            String responseStr = getResponseStr(body);
            wirte(responseStr);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private String getResponseStr(String body) {
        return "Hello,"+body+",Now is"+new java.util.Date(System.currentTimeMillis()).toString();
    }

    private void wirte(String responseStr){
        byte[] bytes = responseStr.getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
        writeBuffer.put(bytes);
        writeBuffer.flip();
        serverChanel.write(writeBuffer,writeBuffer, new CompletionHandler<Integer,ByteBuffer>(){
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                if(attachment.hasRemaining()){//没有写完
                    serverChanel.write(attachment,attachment,this);
                }else{
                    //读取数据
                    //读取数据
                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                    //异步的读
                    serverChanel.read(readBuffer,readBuffer,new ReadHandler(serverChanel));


                }
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                System.out.println("服务端.读取消息失败 ");
                try {
                   serverChanel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        System.out.println("服务端.读取消息失败 ");
        try {
            this.serverChanel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
